extends PanelContainer


@export var task_data:TaskEntity

@onready var start_time_label = %start_time_label
@onready var task_name_label = %task_name_label
@onready var task_description_label = %task_description_label
@onready var task_img = %task_image
@onready var task_progress_label = %task_progress_label
@onready var task_progressbar = %task_progressbar
@onready var remaining_days_label = %remaining_days_label
@onready var finished_tag = %finished_tag
@onready var taskScene = preload("res://pages/task/task.tscn")
@onready var menuButton = %MenuButton

# Called when the node enters the scene tree for the first time.
func _ready():
	if task_data!=null:
		_set_ui_data()
	init_menu_btn()

func init_menu_btn():
	var popMenu = menuButton.get_popup()
	popMenu.index_pressed.connect(_on_menu_item_clicked)

func _on_menu_item_clicked(index:int):
	if index == 0 :
		# 编辑
		var param = {'taskEn':task_data}
		Signalbus.new_action_created.emit(ActionData.new('编辑任务',taskScene,0,param))
	elif index == 1:
		# 删除任务
		del_task()
	
	elif index ==2:
		# 将任务标记为完成
		# 删除未开始的所有schedule, 任务添加一个状态isFinished
		GlobalVariables.del_task_schedules(task_data.tid)
		finished_tag.show()
		task_data.isFinished = true
		GlobalVariables.save_task(task_data)
		Signalbus.task_finished.emit(task_data)
	
func del_task():
		# UI自动删除
		self.queue_free()
		# 从数据中删除
		GlobalVariables.del_task_schedules(task_data.tid)
		GlobalVariables.del_task(task_data)
		Signalbus.task_deled.emit(task_data)

func _set_ui_data():
	task_img.texture = GlobalUtil.create_texture_from_absolute_path(task_data.img_path)
	start_time_label.text = task_data.start_time
	task_name_label.text = task_data.name
	task_description_label.text = task_data.description
	var percent =  (task_data.hours_used / float(task_data.working_hours)*100)
	task_progress_label.text = '%d/%d'%[task_data.hours_used,float(task_data.working_hours)]
	task_progressbar.value = percent
	if task_data.isFinished:
		finished_tag.show()
		remaining_days_label.text = '已完成'
	else:
		finished_tag.hide()
		remaining_days_label.text = '剩余%d天' % [get_last_day_num()]

func get_last_day_num()->int:
	if GlobalVariables.settingData.doScheduleFromToday:
		return GlobalVariables.time_str_2_date(task_data.end_time).days_to(GlobalVariables.get_current_date())+1
	else:
		return GlobalVariables.time_str_2_date(task_data.end_time).days_to(GlobalVariables.get_current_date())
		

func _input(event):
	if event is InputEventMouseButton:
		if event.pressed:
			if event.button_index == MOUSE_BUTTON_LEFT and %remaining_days_label.get_global_rect().has_point(event.position) and Input.get_current_cursor_shape() == 0:
				var param = {'taskEn':task_data}
				Signalbus.new_action_created.emit(ActionData.new('查看任务',taskScene,0,param))

			
